import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { clientsAPI, systemAPI } from '@/services/api'
import { clientsService, dashboardService } from '@/services/dataService'
import { useMockData } from '@/config/app.js'

export const useClientsStore = defineStore('clients', () => {
  const clients = reactive(new Map())
  const screenSharing = reactive(new Map())
  const systemStats = reactive({
    uptime: 0,
    status: '正常'
  })

  // 计算属性
  const onlineClients = computed(() => {
    return Array.from(clients.values()).filter(client => client.status === 'online')
  })

  const totalClients = computed(() => {
    return clients.size
  })

  const onlineClientsCount = computed(() => {
    return onlineClients.value.length
  })

  // 添加或更新客户端
  const updateClient = (clientData) => {
    const existingClient = clients.get(clientData.id)

    const client = {
      id: clientData.id,
      name: clientData.name || clientData.id,
      status: clientData.status || 'offline',
      ip: clientData.ip || '-',
      lastHeartbeat: clientData.lastHeartbeat || new Date().toLocaleString(),
      description: clientData.description || '',
      connectedAt: existingClient?.connectedAt || new Date().toISOString(),
      websocket_url: clientData.websocket_url || '',
      websocket_port: clientData.websocket_port || 0,
      service_status: clientData.service_status || 'unknown',
      screen_sharing: clientData.screen_sharing || false,
      ...clientData
    }

    clients.set(clientData.id, client)
  }

  // 移除客户端
  const removeClient = (clientId) => {
    clients.delete(clientId)
    screenSharing.delete(clientId)
  }

  // 获取客户端
  const getClient = (clientId) => {
    return clients.get(clientId)
  }

  // 根据ID获取客户端（用于屏幕共享）
  const getClientById = (clientId) => {
    // 首先尝试直接查找
    let client = clients.get(clientId)
    if (client) return client

    // 如果没找到，尝试类型转换
    if (typeof clientId === 'string') {
      // 尝试转换为数字
      const numericId = parseInt(clientId)
      if (!isNaN(numericId)) {
        client = clients.get(numericId)
        if (client) return client
      }
    } else if (typeof clientId === 'number') {
      // 尝试转换为字符串
      client = clients.get(clientId.toString())
      if (client) return client
    }

    return null
  }

  // 获取所有客户端列表
  const getClientsList = () => {
    return Array.from(clients.values())
  }

  // 更新客户端状态
  const updateClientStatus = (clientId, status) => {
    const client = clients.get(clientId)
    if (client) {
      client.status = status
      client.lastHeartbeat = new Date().toLocaleString()
      clients.set(clientId, client)
    }
  }

  // 屏幕共享相关
  const updateScreenSharing = (clientId, data) => {
    screenSharing.set(clientId, {
      active: data.active || false,
      imageData: data.imageData || null,
      lastUpdate: new Date().toISOString(),
      resolution: data.resolution || '未知',
      quality: data.quality || '高清',
      ...data
    })
  }

  const getScreenSharing = (clientId) => {
    return screenSharing.get(clientId)
  }

  const isScreenSharingActive = (clientId) => {
    const sharing = screenSharing.get(clientId)
    return sharing?.active || false
  }

  // 启动屏幕共享
  const startScreenSharing = (clientId) => {
    updateScreenSharing(clientId, { active: true })
  }

  // 停止屏幕共享
  const stopScreenSharing = (clientId) => {
    updateScreenSharing(clientId, { active: false, imageData: null })
  }

  // 更新系统统计
  const updateSystemStats = (stats) => {
    Object.assign(systemStats, stats)
  }

  // 清空所有数据
  const clearAll = () => {
    clients.clear()
    screenSharing.clear()
  }

  // 从API加载客户端数据
  const loadClients = async () => {
    try {
      if (useMockData()) {
        // 使用虚拟数据 - 通过 clientsService 获取
        const response = await clientsService.getClients()

        if (response && (response.success !== false)) {
          // 清空现有数据
          clients.clear()

          // 处理虚拟数据响应格式
          let clientsData = []

          if (response.data && response.data.list) {
            clientsData = response.data.list
          } else if (response.data && Array.isArray(response.data)) {
            clientsData = response.data
          } else if (response.list) {
            clientsData = response.list
          } else if (Array.isArray(response)) {
            clientsData = response
          }

          // 添加虚拟数据
          if (Array.isArray(clientsData)) {
            clientsData.forEach(client => {
              updateClient({
                ...client,
                // 确保字段一致性
                lastHeartbeat: client.lastHeartbeat || client.last_heartbeat || new Date().toLocaleString(),
                departmentId: client.departmentId || client.dept_id,
                user: client.user || '未分配'
              })
            })
          } else {
            console.warn('虚拟数据格式不正确，使用内置模拟数据')
            initMockData()
          }
        } else {
          console.warn('虚拟数据API响应异常，使用内置模拟数据')
          initMockData()
        }
      } else {
        // 调用真实API
        const response = await clientsService.getClients()

        if (response && (response.success !== false)) {
          // 清空现有数据
          clients.clear()

          // 处理不同的API响应格式
          let clientsData = []

          if (response.data && response.data.list) {
            // 真实API格式: {code: 200, data: {list: [...]}}
            clientsData = response.data.list
          } else if (response.data && Array.isArray(response.data)) {
            // 备用格式: {code: 200, data: [...]}
            clientsData = response.data
          } else if (response.success && response.data) {
            // 虚拟数据格式: {success: true, data: {list: [...]}}
            clientsData = response.data.list || response.data
          } else if (Array.isArray(response)) {
            // 直接返回数组格式
            clientsData = response
          }

          // 添加新数据
          if (Array.isArray(clientsData)) {
            clientsData.forEach(client => {
              updateClient({
                ...client,
                // 确保字段一致性
                lastHeartbeat: client.lastHeartbeat || client.last_heartbeat || new Date().toLocaleString(),
                departmentId: client.departmentId || client.dept_id,
                user: client.user || '未分配',
                // 修复WebSocket URL字段映射
                websocket_url: client.websocket_url || client.WebSocketURL || '',
                websocket_port: client.websocket_port || client.WebSocketPort || 0,
                service_status: client.service_status || client.ServiceStatus || 'unknown'
              })
            })
          } else {
            console.warn('API返回的客户端数据格式不正确:', clientsData)
            // 如果API数据格式不正确，使用模拟数据作为备用
            initMockData()
          }
        } else {
          console.warn('API返回数据格式异常，使用模拟数据作为备用')
          clients.clear()
          initMockData()
        }
      }
    } catch (error) {
      console.error('加载客户端数据失败:', error)
      // API失败时使用模拟数据作为备用
      clients.clear()
      initMockData()
    }
  }

  // 从API加载系统状态
  const loadSystemStatus = async () => {
    try {
      if (useMockData()) {
        // 使用虚拟数据
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 300))

        // 使用模拟系统状态
        updateSystemStats({
          uptime: Math.floor(Date.now() / 1000) % 86400, // 模拟运行时间
          status: '正常',
          lastUpdate: new Date().toISOString()
        })
      } else {
        // 调用真实API
        const response = await dashboardService.getStats()

        if (response && (response.success !== false)) {
          updateSystemStats({
            uptime: response.system_uptime || response.uptime || 0,
            status: response.system_status || response.status || '正常',
            lastUpdate: new Date().toISOString()
          })
        } else {
          // API失败时使用默认状态
          updateSystemStats({
            uptime: 0,
            status: '未知',
            lastUpdate: new Date().toISOString()
          })
        }
      }
    } catch (error) {
      console.error('加载系统状态失败:', error)
      // API失败时使用默认状态
      updateSystemStats({
        uptime: 0,
        status: '错误',
        lastUpdate: new Date().toISOString()
      })
    }
  }

  // 模拟数据（用于开发测试）
  const initMockData = () => {
    const mockClients = [
      {
        id: 'client-001',
        name: '办公室电脑-001',
        status: 'online',
        ip: '127.0.0.1',
        description: '主办公室台式机',
        websocket_url: 'ws://127.0.0.1:8090/ws',
        websocket_port: 8090,
        service_status: 'active',
        lastHeartbeat: new Date().toLocaleString()
      },
      {
        id: 'client-002',
        name: '会议室电脑-002',
        status: 'online',
        ip: '127.0.0.1',
        description: '会议室投影电脑',
        websocket_url: 'ws://127.0.0.1:8090/ws',
        websocket_port: 8090,
        service_status: 'active',
        lastHeartbeat: new Date().toLocaleString()
      },
      {
        id: 'client-003',
        name: '开发机-003',
        status: 'offline',
        ip: '127.0.0.1',
        description: '开发测试机器',
        websocket_url: '',
        websocket_port: 0,
        service_status: 'inactive',
        lastHeartbeat: new Date(Date.now() - 300000).toLocaleString() // 5分钟前
      }
    ]

    mockClients.forEach(client => {
      updateClient(client)
    })

    // 模拟屏幕共享数据
    updateScreenSharing('client-001', {
      active: false,
      resolution: '1920x1080',
      quality: '高清'
    })
  }

  return {
    clients,
    screenSharing,
    systemStats,
    onlineClients,
    totalClients,
    onlineClientsCount,
    updateClient,
    removeClient,
    getClient,
    getClientById,
    getClientsList,
    updateClientStatus,
    updateScreenSharing,
    getScreenSharing,
    isScreenSharingActive,
    startScreenSharing,
    stopScreenSharing,
    updateSystemStats,
    clearAll,
    loadClients,
    loadSystemStatus,
    initMockData
  }
})
